@page "/post/{slug}"

@using MyBlogServer.Models
@using MyBlogServer.Services
@inject PostService PostService
@inject IJSRuntime JSRuntime
@inject IMarkdownService MarkdownService

@rendermode InteractiveServer

<PageTitle>@_post?.Title</PageTitle>

@if (_post == null)
{
    <div class="blog-container">
        <div class="alert alert-warning">未找到该文章</div>
    </div>
}
else
{
    <div class="blog-container">
        <div class="blog-content-wrapper">
            <article class="blog-post-detail">
                <h1>@_post.Title</h1>
                <div class="meta">
                    <span>发布时间: @_post.CreatedAt.ToString("yyyy年MM月dd日")</span>
                    <!-- 显示阅读数 -->
                    <span class="view-count">阅读数: @_post.ViewCount</span>
                </div>
                <div class="content">
                    @((MarkupString)MarkdownService.ToHtml(_post.Content))
                </div>
                @if (!string.IsNullOrEmpty(_post.Tags))
                {
                    <div class="post-tags">
                        <h4>标签:</h4>
                        @foreach (var tag in _post.Tags.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(t => t.Trim()).Where(t => !string.IsNullOrEmpty(t)))
                        {
                            <a href="/tag/@tag" class="tag">@tag</a>
                        }
                    </div>
                }
            </article>
            
            <aside class="tag-cloud-sidebar">
                <h3>标签云</h3>
                @foreach (var tag in PostService.GetAllTags())
                {
                    <a href="/tag/@tag" class="tag">@tag</a>
                }
            </aside>
        </div>
    </div>
}

@code {
    [Parameter] public string? slug { get; set; }
    private Post? _post;

    protected override async Task OnParametersSetAsync()
    {
        if (!string.IsNullOrEmpty(slug))
        {
            _post = await PostService.GetPostBySlugAsync(slug);
            // 增加阅读数
            if (_post != null)
            {
                _post.ViewCount++;
                await PostService.UpdatePostAsync(_post);
            }
        }
    }
    
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // 调用JavaScript函数为标签分配随机颜色
            await JSRuntime.InvokeVoidAsync("assignRandomTagColors");
        }
    }
}